package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: lutongtong
 * @Date: 2024/10/28/11:17
 * @Description:订单状态异常定时处理
 */
@Component  //实例化实体类，并加入Spring容器中进行管理
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;

    /**
     *定时处理支付超时后未更换正确状态的订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟处理一次
    //    @Scheduled(cron = "1/5 * * * * ? ")  测试
    public void processTimeoutOrder(){
        log.info("定时处理支付超时:{}" , LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.selectStatusErrorOrder(Orders.PENDING_PAYMENT, time);

        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，订单已取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 定时处理一直未点击订单完成的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //    @Scheduled(cron = "0/5 * * * * ? ")  测试
    public void userNotConfirmed(){
        log.info("定时处理订单已完成未点击完成的订单：{}" , LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.selectStatusErrorOrder(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
